package com.diploma.project.aiqiyi.aspect;

import com.diploma.project.aiqiyi.utils.LogUtils;
import com.diploma.project.aiqiyi.utils.ResponseUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Order(2)
@Component
public class HandlerMonitorAspect {

	private static final Logger logger = LoggerFactory.getLogger(HandlerMonitorAspect.class);

	@Pointcut("execution(public * com.diploma.project.aiqiyi..controller..*.*(..))")
	public void handlerMonitor() {

	}

	@Around("handlerMonitor()")
	public Object processHandler(ProceedingJoinPoint pjp) throws Throwable {
		//开始时间
		long startTime = System.currentTimeMillis();

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		if (request == null) {
			throw new Exception("该方法没有HttpServletRequest参数.");
		}

		//打印请求参数
		logger.info(LogUtils.getRequestLog(request));

		Object result = null;
		result = pjp.proceed();

		//请求耗时
		long costTime = System.currentTimeMillis() - startTime;

		logger.info(LogUtils.getResponseLog(costTime, ResponseUtils.getShortResponseContent(result),
				request.getRequestURL().toString()));

		return result;
	}
}
